package com.ithailong.reconsitutionmassion.service.Impl;

import com.ithailong.reconsitutionmassion.dao.Impl.FileDaoImpl;
import com.ithailong.reconsitutionmassion.dao.Impl.UserDaoImpl;
import com.ithailong.reconsitutionmassion.entity.FileModel;
import com.ithailong.reconsitutionmassion.entity.User;
import com.ithailong.reconsitutionmassion.service.FileService;
import com.ithailong.reconsitutionmassion.util.ConstantMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author:hlc
 * date:2023/10/30
 */
@Service
public class FileServiceImpl implements FileService {
   @Autowired
   private FileDaoImpl fileDao;
   @Autowired
   private UserDaoImpl userDao;

   @Value("${my.base.path}")
   private String basePath;

   @Override
   public List<FileModel> selectAllFile(int pageNum, int pageSize, FileModel fileModel) {
      return fileDao.selectAllFile(pageNum, pageSize, fileModel);
   }

   @Override
   public int selectTotal(FileModel fileModel) {
      return fileDao.selectTotal(fileModel);
   }

   @Override
   public void saveFile(MultipartFile file, User user) throws IOException {

      String contentType = file.getContentType();//获取文件类型  image/jpeg
      String name = file.getName();//获取文件名称   fileToUpload
      long size = file.getSize();//获取文件大小  46505
      String originalFilename = file.getOriginalFilename();//1691397906562169139790679.jpg
      //InputStream inputStream = file.getInputStream();//获取到文件的流
      FileModel fileModel = new FileModel();
      fileModel.setName(originalFilename);
      fileModel.setSize(size);
      fileModel.setEnable(1);//设置为1表示可以正常显示连接在页面中
      fileModel.setCreateTime(new Date());
      String[] split = contentType.split("/");
      String url = save(file);
      fileModel.setDownloadLink("/upload/" + url);
      if (user != null) {
         user.setAvatar("/upload/" + url);
         userDao.updateUser(user);
      }
      fileModel.setUploadIp("管理员");
      fileDao.saveFile(fileModel);
   }

   /**
    * 将文件存储到本地
    *
    * @param file
    * @return
    */
   private String save(MultipartFile file) throws IOException {
      String contentType = file.getContentType();
      String[] split = contentType.split("/");
      //判断文件夹是否存在
      File file1 = new File(basePath, split[0]);
      if (!file1.exists()) {
         file1.mkdirs();
      }
      //获取文件的后缀
      String originalFilename = file.getOriginalFilename();//1691397906562169139790679.jpg
      String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
      file.transferTo(new File(file1.getAbsolutePath(), originalFilename));
      return split[0] + "/" + originalFilename;
   }
   public ArrayList<FileModel> isDirectory(File file) {
      //创建一个存储文件的集合{文件集合}
      ArrayList<FileModel> fileList = new ArrayList<>();
      if (file.isDirectory()) {
         File[] files = file.listFiles();
         if (files != null) {
            for (File file1 : files) {
               //此处如果还是文件夹，则继续进行拆分（这里默认情况下【f:/upload】）目录下只有一级目录
               if (file1.isDirectory()) {
                  File[] files1 = file1.listFiles();
                  if (files1 != null) {
                     for (File file2 : files1) {
                        FileModel filesOne = new FileModel();
                        String name = file2.getName();//文件名称
                        String parent = file2.getParent();
                        long length = file2.length();
                        long l = file2.lastModified();//获取文件的时间
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = new Date(l);
                        filesOne.setName(name);
                        filesOne.setSize(length);
                        filesOne.setDownloadLink(parent.replace(ConstantMessage.BASE_PATH, "") + File.separator + name);
                        filesOne.setCreateTime(date);
                        fileList.add(filesOne);
                     }
                  }
               } else {
                  FileModel files1 = new FileModel();
                  String name = file1.getName();//文件名称
                  String parent = file1.getParent();
                  long length = file1.length();
                  long l = file1.lastModified();//获取文件的时间
                  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  Date date = new Date(l);
                  files1.setName(name);
                  files1.setSize(length);
                  files1.setDownloadLink(parent.replace(ConstantMessage.BASE_PATH, "") + File.separator + name);
                  files1.setCreateTime(date);
                  fileList.add(files1);
               }
            }
         }
      }
      return fileList;
   }
}
